package com.study.juc.thread;

import java.io.Serializable;
import java.util.concurrent.*;

/**
 * @program: juc-study
 * @author: jzhou
 * @date: 2022-08-26 11:46
 * @version: 1.0
 * @description: 自定义线程池
 **/
public class ThreadPoolExecutorDemo {
	public static void main(String[] args) {
		//构造一个线程池
		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 4,
				3, TimeUnit.SECONDS,
				new ArrayBlockingQueue<Runnable>(3),
				Executors.defaultThreadFactory(),
				new ThreadPoolExecutor.CallerRunsPolicy());
		//定义最大添加10个线程到线程池中
		int produceTaskMaxNumber = 20;
		for (int i = 1; i <= produceTaskMaxNumber; i++) {
			try {
				//一个任务，并将其加入到线程池
				String work = "work@ " + i;
				System.out.println("put ：" + work);
				threadPool.execute(new ThreadPoolTask(work));
				//便于观察，等待一段时间
//				TimeUnit.SECONDS.sleep(5);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		threadPool.shutdown();
	}
	/**
	 * 线程池执行的任务
	 */
	public static class ThreadPoolTask implements Runnable, Serializable {
		private static final long serialVersionUID = 0;
		//保存任务所需要的数据
		private String threadPoolTaskData;

		ThreadPoolTask(String works) {
			this.threadPoolTaskData = works;
		}

		public void run() {
			//处理一个任务，这里的处理方式太简单了，仅仅是一个打印语句
			System.out.println("start------" + threadPoolTaskData);
			try {
				//便于观察，等待一段时间
				TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(10));
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("------ end" + threadPoolTaskData);
		}
	}
}
